/*
 * @Description: 
 * @Author: Dxcr
 * @Date: 2024-09-05 09:25:38
 * @LastEditTime: 2024-09-05 09:34:07
 * @LastEditors: Dxcr
 */
import axios from 'axios';

import store from '@/store';
import router from '@/router';
import { isArray } from '@/utils/validate';
import { ElMessage } from 'element-plus';

import globalConfig from '@/config';

let loadingInstance;

//处理code异常
const handleCode = (code, msg, data) => {
  // let reg = /^[\u4e00-\u9fa5]s/;
  // console.log('reg.test(data)', data, reg.test(data));
  switch (code) {
    case 40001:
      ElMessage.error(msg || '登录失效');
      // store.dispatch('user/resetAll').catch(() => {})
      break;
    case 40003:
      router.push({ path: '/401' }).catch(() => { });
      break;
    case '-1':
      ElMessage.error(msg === '系统异常' ? data : msg);
      // store.dispatch('user/resetAll').catch(() => {})
      break;
    default:
      ElMessage.error(msg || `后端接口${code}异常`);
      break;
  }
};

//xios初始化
const instance = axios.create({
  baseURL: globalConfig.baseURL,
  timeout: globalConfig.requestTimeout,
  headers: {
    'Content-Type': globalConfig.contentType,
  },
});


//axios请求拦截器
instance.interceptors.request.use(
  config => {
    config.baseURL = config.baseURL || globalConfig.baseURL;
    if (store.getters['accessToken']) config.headers[globalConfig.tokenAuthName] = store.getters['accessToken'];
    if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') config.data = JSON.stringify(config.data);
    // if (debounce.some((item) => config.url.includes(item))) {
    //   //这里写加载动画
    // }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//axios响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.data?.msg_code === 'GetSucc') return response.data
    if (response.data?.msg === '获取成功！') return response.data
    if (loadingInstance) loadingInstance.close();
    const { data, config } = response;
    //如果是文件流直接返回
    if (data instanceof Blob) {
      return data;
    }
    const { code, mesg, data: _data } = data;
    // 操作正常Code数组
    let successCode = globalConfig.successCode;
    const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]];
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      return data;
    } else {
      handleCode(code, mesg, _data);
      return Promise.reject('请求异常拦截:' + JSON.stringify({ url: config.url, code, mesg }) || 'Error');
    }
  },
  error => {
    if (loadingInstance) loadingInstance.close();
    const { response, message } = error;
    if (error.response && error.response.data) {
      const { status, data } = response;
      handleCode(status, data.mesg || message);
      return Promise.reject(error);
    } else {
      let { message } = error;
      if (message === 'Network Error') {
        message = '后端接口连接异常';
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时';
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3);
        message = '后端接口' + code + '异常';
      }
      ElMessage.error(message || `后端接口未知异常`);
      return Promise.reject(error);
    }
  }
);

export default instance;
